# -*- coding: utf-8 -*-

import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from BeautifulSoup import BeautifulSoup
import xmw
from google.appengine.api import mail
from xmw import tianya

from xmw import error
import os
import urllib2, urllib
import uuid
from xmw.db import ds
from google.appengine.ext import webapp
import __main__
from appengine_utilities import sessions
import logging

class MainPage(xmw.RequestHandler):

    def get(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")          
        session_user =None
        if self.sess.has_key("user"):
            session_user=self.sess["user"]
        logging.log( logging.INFO, "forget_password session_user :%s"%str(session_user))
        template_values ={"session_user":session_user,"on_get":True}
        self.render_template(template_values, "../html/forget_password.html")
        return
    def post(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")          
        session_user =None
        if self.sess.has_key("user"):
            session_user=self.sess["user"]
        logging.log( logging.INFO, "forget_password session_user :%s"%str(session_user))
        
        (form_email,e)=self.get_key_from_POST("form_email")
        user_q=ds.User.all()
        user_q.filter('email =', form_email)
        user=user_q.get()
        valid_mail=False
        if user is not None:
            valid_mail=True
            
        template_values ={"session_user":session_user,
                              "on_post":True,
                              "form_email":form_email.encode("utf-8"),
                              "valid_mail":valid_mail,
                              }
            
        self.render_template(template_values, "../html/forget_password.html")
        if valid_mail is True:
            message = mail.EmailMessage(sender="西门外<ximenwai.liu@gmail.com>",
                            subject=u"您在西门外的密码")

            message.to = form_email
            message.body = u"""
    %s 你好!:
            您已经成功在西门外(ximenwai.com)注册用户。
            用户名:%s
            注册email: %s
            注册密码:%s
       """%(user.name,form_email,form_email,user.password)

            message.send()
            return
        

def main():
    application = webapp.WSGIApplication(
                                       [('/forget_password', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
